package cn.itrip.controller;

import cn.itrip.beans.dto.Dto;
import cn.itrip.beans.pojo.ItripUser;
import cn.itrip.beans.vo.ItripTokenVO;
import cn.itrip.common.DtoUtil;
import cn.itrip.common.EmptyUtils;
import cn.itrip.common.ErrorCode;
import cn.itrip.common.MD5;
import cn.itrip.service.TokenService;
import cn.itrip.service.UserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Calendar;

/**
 * 用户名密码验证用户登录
 */
@Controller
@RequestMapping(value="/api")
@Api(value = "API",basePath = "/http://www.itrip.test.cn/auth/api")
public class LoginController {
    @Resource
    private UserService userService;

    @Resource
    private TokenService tokenService;
    //ApiOperation /ApiImplicitParams  Swagger-ui.html的方法描述和参数
    @ApiOperation(value = "用户登录"
                ,httpMethod = "POST"
                ,produces = "HTTP"
                ,protocols = "application/json"
                ,response = Dto.class
                ,notes = "根据用户名密码,进行统一认证")
    @ApiImplicitParams({
            @ApiImplicitParam(paramType = "form",required = true,value = "用户名",name="name",defaultValue = "xxxxx@qq.com")
            ,@ApiImplicitParam(paramType = "form",required = true,value = "密码",name="password",defaultValue = "******")
    })
    @RequestMapping(value = "/dologin",method = RequestMethod.POST,produces = "application/json")
    public @ResponseBody Dto doLogin(@RequestParam String name
                                    ,@RequestParam String password
                                    ,HttpServletRequest request){

        if (!EmptyUtils.isEmpty(name) && !EmptyUtils.isEmpty(password)){
            ItripUser user =null;
            try {
                //加密后去数据库中匹配用户名
                user =userService.login(name.trim(),MD5.getMd5(password.trim(),32));
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (EmptyUtils.isNotEmpty(user)){
                //生成token
                String token = tokenService.generateToken(
                        request.getHeader("user-agent"), user);
                //保存token至redis
                tokenService.save(token, user);
                //提示用户登录成功
                //返回ItripTokenVO
                ItripTokenVO tokenVO=new ItripTokenVO(token,
                        Calendar.getInstance().getTimeInMillis()+2*60*60*1000,//2h有效期
                        Calendar.getInstance().getTimeInMillis());

                return DtoUtil.returnDataSuccess(tokenVO);

            }
        }


        return DtoUtil.returnFail("用户名或者密码错误",ErrorCode.AUTH_AUTHENTICATION_FAILED);
    }


}
